package com.nwcl.basic.service.impl;

import com.nwcl.basic.bo.OrdersBO;
import com.nwcl.basic.dao.OrdersDao;
import com.nwcl.basic.entity.Goods;
import com.nwcl.basic.entity.Orders;
import com.nwcl.basic.service.OrdersService;
import com.nwcl.common.result.Page;
import com.nwcl.common.utils.BeanUtil;
import com.nwcl.common.utils.DateUtil;
import com.nwcl.ysx.request.OrdersPageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liguiqin
 * @date 2023/5/26
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersDao ordersDao;

    @Override
    public Integer save(OrdersBO ordersBO) {
        Orders orders = BeanUtil.copy(ordersBO, Orders.class);
        ordersDao.save(orders);
        return orders.getId();
    }

    @Override
    public String generateOrderCode(Integer type) {
        //生产订单号规则=yyMMddHHmmssSSS+type+四位随机数
        String orderCode = DateUtil.formatDate(new Date(), "yyMMddHHmmssSSS") + type;
        orderCode += Math.round((Math.random() + 1) * 1000);//四位随机
        return orderCode;
    }

    @Override
    public OrdersBO getOrderByCode(String orderCode) {
        Orders orders = ordersDao.getOrderByCode(orderCode);
        if (orders != null) {
            return BeanUtil.copy(orders, OrdersBO.class);
        }
        return null;
    }

    @Override
    public void updateOrderStatus(String orderCode, Integer status,Date payTime) {
        ordersDao.updateOrderStatus(orderCode, status,payTime);
    }

    @Override
    public Page<OrdersBO> page(OrdersPageRequest param) {
        Page<OrdersBO> resultPage = new Page<>();
        List<Goods> modelList = ordersDao.list(param.getUserId());
        if (CollectionUtils.isEmpty(modelList)) {
            resultPage = new Page<>(param.getPageNum(), param.getPageSize(), 0, new ArrayList<>());
            return resultPage;
        }
        List<OrdersBO> boList = BeanUtil.copyList(modelList, OrdersBO.class);
        //手工设置分页信息
        resultPage = new Page(param.getPageNum(), param.getPageSize(), boList.size(), boList);
        resultPage = Page.getPageList(resultPage);
        return resultPage;
    }

    @Override
    public OrdersBO getByIdAndUserId(Integer id, Integer userId) {
        Orders orders =  ordersDao.getByIdAndUserId(id,userId);
        if(null!=orders){
            return BeanUtil.copy(orders,OrdersBO.class);
        }
        return null;
    }

    @Override
    public Integer countByUserId(Integer userId) {
        return ordersDao.countByUserId(userId);
    }
}
